package com.changgou.search.exception;

import com.changgou.entity.EResultCode;
import com.changgou.entity.Result;
import com.changgou.entity.ResultCode;
import com.changgou.entity.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;


/**
 * 统一异常处理类
 */
@ControllerAdvice
public class BaseExceptionHandler {

    Logger logger = LoggerFactory.getLogger(BaseExceptionHandler.class);

    private static Map<Class<? extends Exception>, EResultCode> map = new HashMap<>();

    static {
        map.put(TimeoutException.class, EResultCode.TIMEOUT_);
        map.put(IllegalArgumentException.class, EResultCode.PARAM_ERROR);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result error(Exception e) {
        logger.error(e + ""); //打印日志
        // 如果 异常类型为 MyBusinessException，则从成员属性 取ResultCode
        /*if (e.getClass() == MyBaseException.class) {
            return new Result(((MyBaseException) e).getResultCode());
        }*/
        EResultCode resultCode = map.get(e.getClass());
        // 如果查不到，则return new Result(false,2001,"对不起，服务出现了未知异常，请稍后重试");
        if (resultCode == null) {
            return new Result(false, StatusCode.ERROR, "对不起，服务出现了未知异常，请稍后重试");
        }
        // 如果查到，则return new Result(ResultCode);
        return new Result(resultCode);
    }

    @ExceptionHandler(value = MyBaseException.class)
    @ResponseBody
    public Result error(MyBaseException e) {
        logger.error(e + ""); //打印日志
        ResultCode resultCode = e.getResultCode();
        return new Result(resultCode);
    }
}
